<?php
namespace App\Services\Fund\Withdraw;
use App\Services\Fund\ValidateWithdraw;
use App\Models\Fund\Withdraw;
use App\Models\Fund\FundAccount;
use Illuminate\Support\Facades\DB;
class WithdrawLogic
{
    /*我的 - 申请提现*/
    /*public function applyDrawwith($data): array 
    {
        $this->db()->startTrans();
        try{
            //申请提现记录表中添加记录 + 冻结该用户资金
            $data['review_info'] = [];
            $data['transfer_info'] = [];
            $addWithdraw = $this->model($this->withdrawModel)->allowField($this->allowField)->save($data);
            $freezeData['obj_id'] = $this->model($this->withdrawModel)->getLastInsID();
            $freezeData['user_id'] = $data['user_id'];
            $freezeData['opposite_id'] = SYSTEM_ID;
            $freezeData['money'] = $data['money'];
            $freezeData['update_ip'] = $data['update_ip'];
            $freezeData['app_id'] = $data['app_id'];
            $freezeData['user_info'] = json_encode($data['user_info']);
            $freezeData['opposite_info'] = isset($data['opposite_info']) ? $data['opposite_info'] : json_encode(['name'=>'system']);
            $freezeData['type'] = 'withdraw';
            $freezeData['freeze_counts'] = 1;
            $freezeRes = logic('\app\serverfund\logic\FundAccount')->freeze($freezeData);
            if($freezeRes['status'] != SUCCESS_STATUS){
                return $freezeRes;
            }
            // 提交事务
            $this->db()->commit();
        } catch (\Exception $e) {
            // 回滚事务
            $this->db()->rollback();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($freezeRes);

    }*/

    /*我的 - 申请提现列表（分页）************/
    public function withdrawList($data): array 
    {
       $keywords   = $data['keywords'];
       if(isset($data['status']) && $data['status'] !== ''){
          $raw = Withdraw::where('status','=',$data['status']); 
        }else{
          $raw = Withdraw::whereIn('status',[0,1,2,3,4]);
        }
        if(isset($data['keywords']) && !empty($data['keywords'])){ 
             $raw->where(function ($query) use ($keywords) {
                $query->orWhere('user_info->name','like',"%{$keywords}%")
                      ->orWhere('user_info->id','like',"%{$keywords}%")
                      ->orWhere('card_info->name','like',"%{$keywords}%")
                      ->orWhere('card_info->number','like',"%{$keywords}%");
               });
         }
        if(isset($data['user_id']) && !empty($data['user_id'])){ $raw->where('user_id','=',$data['user_id']);}
        if(isset($data['time']) && !empty($data['time'])){
            $threeMonthTime = mktime(0, 0, 0, date("m")-3, date("d"), date("Y"));
            if($data['time'] == 'threeMonthAgo'){  
               $raw->where('create_time','<',$threeMonthTime);   //3个月以前
            }elseif($data['time'] == 'threeMonth'){   
               $raw->where('create_time','>',$threeMonthTime); //3个月之内
            }
        }
        $res = $raw->orderBy('id', 'desc')->paginate($data['listRows'], null, null, $data['page'])->toArray();         
        return auto_return_page($res, '已找到提现列表数据', '没有提现列表数据');
    }

    /*管理员 - 审核提现**************************************/
    /*审核成功：修改为审核成功状态
    审核失败：修改为审核失败状态 + 解冻用户资金*/
    public function auditWithdraw($data): array 
    {
         DB::beginTransaction();
        try{
            //修改提现记录状态
            $_where['id'] = $data['id'];
            $_where['status'] = 0;
            $withdrawInfo = Withdraw::where($_where)->first();
            if(!$withdrawInfo){
                return verify_err(null, '未找到相应的提现记录');
            }

            $saveData['status'] = $data['status'];
            $saveData['review_id'] = $data['review_id'];
            $saveData['review_info'] = json_encode($data['review_info']);
            $updateRes = Withdraw::where($_where)->update($saveData);

            if($data['status'] == 2){  //审核失败：解冻用户资金
                $unfreezeData['user_id'] = $withdrawInfo['user_id'];
                $unfreezeData['opposite_id'] = $data['review_id'];
                $unfreezeData['type'] = 'withdraw';
                $unfreezeData['obj_id'] = $data['id'];
                $unfreezeData['freeze_counts'] = 1;
                $unfreezeData['money'] = $withdrawInfo['money'];
                $unfreezeData['update_ip'] = $data['update_ip'];
                $unfreezeData['app_id'] = $withdrawInfo['app_id'];
                $unfreezeData['user_info'] = json_encode($withdrawInfo['user_info']);
                $unfreezeData['opposite_info'] = json_encode($data['review_info']);
                $unfreezeRes = (new \App\Services\Fund\FundAccount\FundAccountLogic())->unfreeze($unfreezeData);
                if($unfreezeRes['status'] != SUCCESS_STATUS){
                    return $unfreezeRes;
                }
            }
            // 提交事务
            DB::commit();
        }catch (\Exception $e) {
            // 回滚事务
             DB::rollback();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($updateRes);
    }

    /*管理员 - 审核转账**************************************************
      转让成功： 修改为转让成功状态 + 解冻用户资金 + 用户资金转让给平台
      转让失败： 修改为转让失败状态 + 解冻用户资金
    */
    public function auditTransfer($data): array 
    {
        $_where['id'] = $data['id'];
        $_where['status'] = 1;
        $saveData['status'] = $data['status'];
        $saveData['transfer_id'] = $data['transfer_id'];
        $saveData['transfer_info'] = json_encode($data['transfer_info']);
        //开启事务
        DB::beginTransaction();
        try{
            $withdrawInfo = Withdraw::where($_where)->first();
            if(!$withdrawInfo){
                return verify_err(null, '未找到相应的提现记录');
            }
            //修改状态
            $res = Withdraw::where($_where)->update($saveData);
            //解冻用户资金
            $unfreezeData['user_id'] = $withdrawInfo['user_id'];
            $unfreezeData['opposite_id'] = $data['transfer_id'];
            $unfreezeData['type'] = 'withdraw';
            $unfreezeData['obj_id'] = $data['id'];
            $unfreezeData['freeze_counts'] = 1;
            $unfreezeData['money'] = $withdrawInfo['money'];
            $unfreezeData['update_ip'] = $data['update_ip'];
            $unfreezeData['app_id'] = $withdrawInfo['app_id'];
            $unfreezeData['user_info'] = json_encode($withdrawInfo['user_info']);
            $unfreezeData['opposite_info'] = json_encode($data['transfer_info']);
            $unfreezeRes = (new \App\Services\Fund\FundAccount\FundAccountLogic())->unfreeze($unfreezeData);
            if($unfreezeRes['status'] != SUCCESS_STATUS){
                return $unfreezeRes;
            }
            if($data['status'] == 4){ //后台转账成功给用户后： 用户资金支付给平台
                $transferData['user_id'] = $withdrawInfo['user_id'];
                $transferData['opposite_id'] = SYSTEM_ID;
                $transferData['money'] = $withdrawInfo['money'];
                $transferData['update_ip'] = $data['update_ip'];
                $transferData['app_id'] = $data['app_id'];
                $transferData['user_info'] = json_encode($withdrawInfo['user_info']);
                $transferData['opposite_info'] = json_encode(['name'=>'system']);
                $transferRes = (new \App\Services\Fund\FundAccount\FundAccountLogic())->transfer($transferData);
                if($transferRes['status'] != SUCCESS_STATUS){
                    return $transferRes;
                }
            }
            // 提交事务
             DB::commit();
        }catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
        return auto_return($res);
    }
}